<template>
    <div class="engine-template-wrapper">
        <!--swiper-->
        <div class="swiper-container">
            <div class="swiper-wrapper">
                <div class="swiper-slide flat relative" v-for="(page, i) in pageData.pages" :key="i">
                    <!--页面内容区域-->
                    <div class="quark-page-wrapper"
                         :style="getCommonStyle({...page.commonStyle, top: pageTop, height: pageData.height, width: pageData.width, position: 'relative'}, scalingRatio)">
                        <componentsTemplate
                            v-for="(item, index) in page.elements"
                            :key="index"
                            :loaded="item._loaded"
                            @handleElementClick="handleElementClick"
                            :element="item"
                            :style="getCommonStyle(item.commonStyle, scalingRatio)">
                        </componentsTemplate>
                    </div>
                </div>
            </div>
            <div class="swiper-pagination"></div><!--分页器。如果放置在swiper-container外面，需要自定义样式。-->
        </div>
    </div>
</template>

<script>
//import editorProjectConfig from '@client/pages/editor/DataModel'
import componentsTemplate from './components-template'
import {getPage} from "../../api/api";
import _ from 'lodash'

/**
 * 获取元素样式
 * @param styleObj
 * @param scalePoint 缩放比例
 */
let getCommonStyle = function (styleObj, scalingRatio = 1) {

    let needUnitStr = ['width', 'height', 'top', 'left', 'paddingTop', 'paddingLeft', 'paddingRight', 'paddingBottom', 'marginTop', 'marginLeft', 'marginRight', 'marginBottom', 'borderWidth', 'fontSize', 'borderRadius', 'letterSpacing']
    let style = {}

    for (let key in styleObj) {
        if (needUnitStr.includes(key)) {
            style[key] = (styleObj[key] * scalingRatio) + 'px'
        } else {
            style[key] = styleObj[key]
        }
    }
    style.transform = `rotate(${style.rotate}deg)`
    style.backgroundImage = style.backgroundImage ? `url(${style.backgroundImage})` : '';
    return style;
}

export default {
    name: 'engineH5Swiper',
    components: {
        componentsTemplate
    },
    props: {
        src: {
            type: String,
            default: ''
        },
        isRatio: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            getCommonStyle: getCommonStyle,
            scalingRatio: 1,
            pageData: {
                pages: []
            },
            pageTop: 0,
            activeIndex: 0,
            loading: false
        }
    },
    mounted() {

        /* setTimeout(()=>{
             this.init();
         },500);*/

        this.init();

        let that = this;
        // 判断翻页类型
        var direction = this.pageData.flipType === 0 ? 'vertical' : 'horizontal'
        var showSlideNumber = !!this.pageData.slideNumber
        new window.Swiper('.swiper-container', {
            direction: direction,
            loop: false,
            pagination: showSlideNumber ? {el: '.swiper-pagination'} : {},
            scrollbar: {
                el: '.swiper-scrollbar',
            },
            on: {
                slideChange: function () {
                    that.onSwipe(this.activeIndex);
                },
            },
        });
    },
    methods: {
        /*async init() {

            console.log("aaaa",typeof this.loading, this.loading)

            if (this.loading) return;
            this.loading = true;

            await getPage(this.src).then(res => {

                console.log("bbbbbbbb",typeof this.loading, this.loading)

                console.log("res==", res)
                this.loading = false;
                if (res.code == 200) {
                    this.pageData = res.data;
                    this.config();
                }
            }).catch(err => {
                this.loading = false;
            })
        },*/
        init: _.throttle(function () {

            if (this.loading) return;
            this.loading = true;

            getPage(this.src).then(res => {

                this.loading = false;
                if (res.code == 200) {
                    this.pageData = res.data;
                    this.config();
                }
            }).catch(err => {
                this.loading = false;
            })
        }, 500),
        config(data) {

            //let pageData = window._pageData;
            //this.scalingRatio = document.body.clientWidth / $config.canvasH5Width;
            this.scalingRatio = this.isRatio ? document.body.clientWidth / this.pageData.width : 1;
            //this.pageTop = (document.documentElement.clientHeight - this.pageData.height * this.scalingRatio) / 2
            this.pageTop = Math.max(this.pageTop, 0);

            // 将组件加个状态标识
            this.pageData.pages.forEach((page, index) => {
                page.elements.forEach(e => {
                    e._loaded = (index === 0);
                })
            })
            //this.pageData = pageData;
        },
        onSwipe(index) {
            this.activeIndex = index;
            this.pageData.pages[this.activeIndex].elements.forEach(e => {
                e._loaded = true;
            })
        },
        /**
         * 按钮点击事件
         * @param eventsData
         */
        async handleElementClick(eventsData, element) {
            for (let i = 0, len = eventsData.length; i < len; i++) {
                if (this['_event_' + eventsData[i].type]) {
                    await this['_event_' + eventsData[i].type](eventsData[i], element, this.pageData)
                }
            }
        }
    }
}
</script>

<style scoped>

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

html, body, #app {
    position: relative;
    width: 100%;
    height: 100%;
}

.qk-image img {
    width: 100%;
}

.engine-template-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
}

/deep/ .qk-image-carsousel {
    height: 100%;
}


.relative {
    position: relative;
}

.hidden {
    overflow: hidden;
}
</style>
